package com.atom.common.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.atom.common.entity.NumberDO;

@Repository
public class NumberDao extends AvensCommonDao<NumberDO> {
  
  public int getNumber(String procDefKey, int year) {
    List<NumberDO> list = super.findByProperty("procDefKey", procDefKey);
    if (list == null || list.isEmpty()) {
      NumberDO instance = new NumberDO();
      instance.setNumber(2);
      instance.setProcDefKey(procDefKey);
      instance.setYear(year);
      super.save(instance);
      return 1;
    }
    
    NumberDO instance = list.get(0);
    int temp = 1;
    if (year == instance.getYear()) {
      temp = instance.getNumber();
      instance.setNumber(temp + 1);      
    } else {
      instance.setYear(year);
      instance.setNumber(temp + 1);
    }
    super.update(instance);
    return temp;    
  }

  public int findNumber(String procDefKey, int year) {
    List<NumberDO> list = super.findByProperty("procDefKey", procDefKey);
    if (list == null || list.isEmpty()) {
      NumberDO instance = new NumberDO();
      instance.setNumber(1);
      instance.setProcDefKey(procDefKey);
      instance.setYear(year);
      super.save(instance);
      return 1;
    } else {
      return list.get(0).getNumber();
    }
  }

  
}
